#!/bin/bash
# 使用此脚本需要确保/usr/local/src目录下有zabbix-5.2.0.tar.gz文件

# 安装zabbix-agent
yum -y install gcc pcre-devel autoconf
useradd zabbix -r -s /sbin/nologin
cd /usr/local/src
tar -zxf zabbix-5.2.0.tar.gz
cd zabbix-5.2.0/
./configure --enable-agent --prefix=/usr/local/zabbix/
make && make install

# 服务器IP地址,主动模式服务器IP地址
while :
do
    read -p "请输入zabbix服务器IP地址：" server_ip
    echo $server_ip | egrep "(^([1-9]|1[0-9]|1[1-9]{2}|2[0-4][0-9]|25[0-5])\.)(([0-9]{1,2}|1[1-9]{2}|2[0-4][0-9]|25[0-5])\.){2}([1-9]|[1-9][0-9]|1[1-9]{2}|2[0-5][0-9]|25[0-4])$" > /dev/null;
    if [ $? -eq 0 ]
	then
	    sed -ri "/^Server=/s/=.*/=$server_ip/" /usr/local/zabbix/etc/zabbix_agentd.conf
	    sed -ri "/^ServerActive=/s/=.*/=$server_ip/" /usr/local/zabbix/etc/zabbix_agentd.conf
	    break
	else
	    echo "您输入的IP地址格式不正确。"
    fi
done

# zabbix主机名
sed -ri "/^Hostname=/s/=.*/=`hostname`/"  /usr/local/zabbix/etc/zabbix_agentd.conf

# 允许不安全脚本传参
sed -ri "/^# Unsafe/s/# //" /usr/local/zabbix/etc/zabbix_agentd.conf
sed -ri "/^Unsafe/s/0/1/" /usr/local/zabbix/etc/zabbix_agentd.conf

# 设置TCP连接处理延迟
sed -ri "/^# Timeout/s/# //" /usr/local/zabbix/etc/zabbix_agentd.conf
sed -ri "/^Timeout/s/3/15/" /usr/local/zabbix/etc/zabbix_agentd.conf

# 添加启动管理文件
cat >> /usr/lib/systemd/system/zabbix_agentd.service <<-'EOF'
[Unit]
Description=zabbix agent
After=network.target remote-fs.target nss-lookup.target

[Service]
Type=forking
PIDFile=/tmp/zabbix_agentd.pid
ExecStart=/usr/local/zabbix/sbin/zabbix_agentd -c /usr/local/zabbix/etc/zabbix_agentd.conf
ExecStop=/bin/kill $MAINPID

[Install]
WantedBy=multi-user.target
EOF

# 启动zabbix-agentd
systemctl restart zabbix_agentd
systemctl enable zabbix_agentd
ss -ntul | grep 10050
